<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\model\ContractPrice;
use think\facade\Config;
use think\facade\Db;
use think\Request;
use app\model\Contract as Model;

class Contract extends BaseController
{
    /**
     * 列表查询
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request)
    {
        $params = $request->param();
        $page   = isset($params['page']) ? $params['page'] : 1;
        $limit  = isset($params['limit']) ? $params['limit'] : 10;
        $where  = [
            ['delete_time', '=', 0]
        ];
        if (isset($params['name']) && !empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (isset($params['linker_name']) && !empty($params['linker_name'])) {
            $where[] = ['linker_name', 'like', "%{$params['linker_name']}%"];
        }
        if (isset($params['projectId']) && !empty($params['projectId'])) {
            $where[] = ['project_id', 'in', $params['projectId']];
        }
        if (isset($params['status']) && $params['status'] != '') {
            $where[] = ['status', '=', $params['status']];
        }
        $pageLimit = [
            'page'      => $page,
            'list_rows' => $limit,
        ];
        $paginate  = Model::where($where)
            ->with('projectInfo')
            ->order('id', 'desc')
            ->paginate($pageLimit);
        $dataList  = $paginate->toArray();
        foreach ($dataList['data'] as &$item) {
            $payed               = ContractPrice::where('contract_id', $item['id'])->sum('payment');
            $levelTotal          = ContractPrice::where('contract_id', $item['id'])->count();
            $level               = ContractPrice::where("contract_id={$item['id']} and payment!=0")->count();
            $item['level']       = $level;
            $item['level_total'] = $levelTotal;
            $item['payed']       = $payed;
        }
        return $this->repData([
            'totalNum' => $dataList['total'],
            'list'     => $dataList['data']
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 项目添加
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function save(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'name'       => 'require',
            'price'      => 'require',
            'pay_type'   => 'require',
            'project_id' => 'require',
        ], [
            'name.require'       => '合同名称不能为空',
            'price.require'      => '合同金额不能为空',
            'pay_type.require'   => '付费方式必选',
            'project_id.require' => '所属项目必选',
        ]);

        try {
            Db::startTrans();
            $nowTime = $request->time();
            $data    = [
                'name'               => $params['name'],
                'project_id'         => $params['project_id'],
                'price'              => $params['price'],
                'develop_time_start' => isset($params['develop_date'][0]) ? strtotime($params['develop_date'][0]) : 0,
                'develop_time_end'   => isset($params['develop_date'][1]) ? strtotime($params['develop_date'][1]) : 0,
                'status'             => $params['status'],
                'pay_type'           => $params['pay_type'],
                'linker_name'        => $params['linker_name'],
                'document_path'      => $params['document_path'],
                'contract_path'      => $params['contract_path'],
                'linker_phone'       => $params['linker_phone'],
                'remark'             => isset($params['remark']) ? $params['remark'] : '',
                'create_time'        => $nowTime,
                'update_time'        => $nowTime,
                'delete_time'        => 0,
            ];
            $result  = Model::create($data);
            if (!isset($result->id) || $result->id < 0) {
                return $this->error();
            }
            $contract_id  = $result->id;
            $contractData = [];
            $tempNum      = ['一', '二', '三', '四'];
            foreach ($params['money_list'] as $k => $item) {
                $item = json_decode($item, true);
                if (isset($params['money_list'][$k - 1])) {
                    $beforeItem = json_decode($params['money_list'][$k - 1], true);
                    if (!empty($item['payment']) && empty($beforeItem['payment'])) {
                        throw new \Exception(($tempNum[$k - 1]) . '期款项不能为空！');
                    }
                }
                $item['price'] = '0.00';
                if ($k == 0) {
                    switch ($params['pay_type']) {
                        case 1:
                        case 4:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 2:
                            $item['price'] = number_format($params['price'] * (5 / 10), 2, '.', '');
                            break;
                        case 3:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 1) {
                    switch ($params['pay_type']) {
                        case 1:
                        case 3:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 2:
                            $item['price'] = number_format($params['price'] * (5 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 2) {
                    switch ($params['pay_type']) {
                        case 1:
                            $item['price'] = number_format($params['price'] * (4 / 10), 2, '.', '');
                            break;
                        case 3:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 3) {
                    switch ($params['pay_type']) {
                        case 3:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                $item['contract_id'] = $contract_id;
                $item['payment']     = !empty($item['payment']) ? $item['payment'] : '0.00';
                $contractData[]      = $item;
            }

            $contractPriceModel = new ContractPrice();
            $result             = $contractPriceModel->saveAll($contractData);
            if (!$result) {
                throw new \Exception('付费流程保存失败！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $errorMessage = $e->getMessage();
            return $this->error($errorMessage);
        }
        return $this->success('保存成功！', ['id' => $contract_id]);
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $dataModel = Model::find($id);
        if (!$dataModel || $dataModel->delete_time != 0) {
            return $this->error('合同信息不存在！');
        }
        $contractPrice           = new ContractPrice;
        $contractPriceData       = $contractPrice->where('contract_id', $id)->select();
        $dataModel->develop_date = [
            empty($dataModel->develop_time_start) ? '' : date('Y-m-d', $dataModel->develop_time_start),
            empty($dataModel->develop_time_end) ? '' : date('Y-m-d', $dataModel->develop_time_end),
        ];
        $dataModel->money_list   = $contractPriceData;
        return $this->repData($dataModel);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {

    }

    /**
     * 更新项目信息
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $params = $request->param();
        $this->validate($params, [
            'name'       => 'require',
            'price'      => 'require',
            'pay_type'   => 'require',
            'project_id' => 'require',
        ], [
            'name.require'       => '合同名称不能为空',
            'price.require'      => '合同金额不能为空',
            'pay_type.require'   => '付费方式必选',
            'project_id.require' => '所属项目必选',
        ]);
        try {
            Db::startTrans();
            $nowTime = $request->time();
            $data    = [
                'name'               => $params['name'],
                'project_id'         => $params['project_id'],
                'price'              => $params['price'],
                'develop_time_start' => isset($params['develop_date'][0]) ? strtotime($params['develop_date'][0]) : 0,
                'develop_time_end'   => isset($params['develop_date'][1]) ? strtotime($params['develop_date'][1]) : 0,
                'status'             => $params['status'],
                'pay_type'           => $params['pay_type'],
                'linker_name'        => $params['linker_name'],
                'linker_phone'       => $params['linker_phone'],
                'remark'             => isset($params['remark']) ? $params['remark'] : '',
                'document_path'      => $params['document_path'],
                'contract_path'      => $params['contract_path'],
                'update_time'        => $nowTime,
            ];
            $result  = (new Model)->where('id', $id)->save($data);
            if (!$result) {
                throw new \Exception('合同信息更新失败');
            }
            $contract_id  = $id;
            $contractData = [];
            $tempNum      = ['一', '二', '三', '四'];
            foreach ($params['money_list'] as $k => $item) {
                $item = json_decode($item, true);
                if (isset($params['money_list'][$k - 1])) {
                    $beforeItem = json_decode($params['money_list'][$k - 1], true);
                    if (!empty($item['payment']) && empty($beforeItem['payment'])) {
                        throw new \Exception(($tempNum[$k - 1]) . '期款项不能为空！');
                    }
                }
                $item['price'] = '0.00';
                if ($k == 0) {
                    switch ($params['pay_type']) {
                        case 1:
                        case 4:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 2:
                            $item['price'] = number_format($params['price'] * (5 / 10), 2, '.', '');
                            break;
                        case 3:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 1) {
                    switch ($params['pay_type']) {
                        case 1:
                        case 3:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 2:
                            $item['price'] = number_format($params['price'] * (5 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 2) {
                    switch ($params['pay_type']) {
                        case 1:
                            $item['price'] = number_format($params['price'] * (4 / 10), 2, '.', '');
                            break;
                        case 3:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                    }
                }
                if ($k == 3) {
                    switch ($params['pay_type']) {
                        case 3:
                            $item['price'] = number_format($params['price'] * (3 / 10), 2, '.', '');
                            break;
                        case 4:
                            $item['price'] = number_format($params['price'] * (2 / 10), 2, '.', '');
                            break;
                    }
                }
                $item['contract_id'] = $contract_id;
                $item['payment']     = !empty($item['payment']) ? $item['payment'] : '0.00';
                $contractData[]      = $item;
            }

            $contractPriceModel = new ContractPrice();
            $result             = $contractPriceModel->saveAll($contractData);
            if (!$result) {
                throw new \Exception('付款流程保存失败！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $errorMessage = $e->getMessage();
            return $this->error($errorMessage);
        }
        return $this->success('保存成功！', ['id' => $contract_id]);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $dataModel = Model::find($id);
        if (!$dataModel || $dataModel->delete_time != 0) {
            return $this->error('合同信息不存在');
        }
        $data   = [
            'id'          => $id,
            'delete_time' => time(),
        ];
        $result = $dataModel->save($data);
        if (!$result) {
            return $this->error();
        }
        return $this->success();
    }

    public function upload()
    {
        $file      = request()->file('file');
        $extension = $file->extension();
        $fileName  = str_replace('.' . $extension, '', $file->getOriginalName()) . '_' . date('Y-m-d_His');
        $fileName  = $fileName . '.' . $extension;
        $savename  = \think\facade\Filesystem::putFileAs('project', $file, $fileName);
        $saveDir   = Config::get('filesystem.disks.local.url');
        $fileUrl   = request()->domain() . implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, 3)) . $saveDir . '/' . $savename;
        return $this->success('上传文件成功', ['filePath' => $fileUrl]);
    }
}
